//
//  AudioPlayer.m
//  app
//
//  Created by yanjunliang on 2024/9/9.
//

#import "AudioPlayer.h"
#import <AVFoundation/AVFoundation.h>

@interface AudioPlayer()

@property (nonatomic, strong) AVAudioPlayer *audioPlayer;

@end

@implementation AudioPlayer

- (void)play:(NSString *)path {
    NSString *homePathString = [[NSBundle mainBundle] pathForResource:@"arkui-x" ofType:nil];
    NSString *urlString = [NSString stringWithFormat:@"%@/entry/resources/rawfile/%@",homePathString,path];
    NSURL *fileUrl = [NSURL URLWithString:urlString];
    
    if (self.audioPlayer != nil) {
        [self.audioPlayer stop];
        self.audioPlayer = nil;
    }
    NSError *error = nil;
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
    if (self.audioPlayer) {
        [self.audioPlayer play];
    } else {
        NSLog(@"Failed to initialize audio player: %@", [error localizedDescription]);
    }
}

- (void)stop {
    if (self.audioPlayer != nil) {
        [self.audioPlayer stop];
        self.audioPlayer = nil;
    }
}

@end
